package com.zhj.edu.iotserver.service.impl;

import com.alibaba.druid.util.StringUtils;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zhj.edu.bo.Account;
import com.zhj.edu.bo.SecurityUser;
import com.zhj.edu.iotserver.mapper.TenantMapper;
import com.zhj.edu.iotserver.mapper.UserRoleMapper;
import com.zhj.edu.pojo.Menu;
import com.zhj.edu.pojo.Role;
import com.zhj.edu.pojo.Tenant;
import com.zhj.edu.pojo.User;
import com.zhj.edu.iotserver.mapper.UserMapper;
import com.zhj.edu.iotserver.service.UserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhj.edu.vo.LoginVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 管理员用户表 服务实现类
 * </p>
 *
 * @author xiaobobo
 * @since 2024-09-13
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService , UserDetailsService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private UserRoleMapper userRoleMapper;

    @Autowired
    private TenantMapper tenantMapper;

    @Override
    public UserDetails loadUserByUsername(String loginVoJsonStr) throws UsernameNotFoundException {
        //拿到这个信息之后，首先-弄成Java对象
        LoginVo loginVo = JSON.parseObject(loginVoJsonStr, LoginVo.class);
        //取出用户名和type
        //前端页面传递的用户名
        String username = loginVo.getUsername();
        Integer type = loginVo.getType();
        if (StringUtils.isEmpty(username) || null==type){
            throw new UsernameNotFoundException("用户名不对或者type未传递");
        }
        SecurityUser securityUser = new SecurityUser();
        //执行到这里 说明参数是对的
        if (type==0){
            //说明是管理员登录
            return userLogin(username, securityUser, 0);
        }else {
            //说明是会员登录
            tenatLogin(username, securityUser);
        }
        return securityUser;
    }

    /**
     * 会员登录
     * @param username
     * @param securityUser
     */
    private void tenatLogin(String username, SecurityUser securityUser) {
        //首先通过用户名查询租户信息
        QueryWrapper<Tenant> tenantQueryWrapper = new QueryWrapper<>();
        tenantQueryWrapper.eq("name", username);
        Tenant tenant = tenantMapper.selectOne(tenantQueryWrapper);
        if (null==tenant){
            //说明用户名不对
            throw new UsernameNotFoundException("用户名不对");
        }
        //执行到此处，说明用户名是对的,就封装参数
        Account account = new Account();
        account.setType(1);
        account.setId(tenant.getId());
        account.setUsername(tenant.getName());
        account.setPassword(tenant.getPwd());
        securityUser.setAccount(account);
        securityUser.setRoleAndPerms(new ArrayList<>());
    }

    /**
     * 管理员登录
     * @param username
     * @param securityUser
     * @return
     */
    private SecurityUser userLogin(String username, SecurityUser securityUser, Integer type) {

        //通过用户名查询用户对象
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("username", username);
        User userSelect = userMapper.selectOne(userQueryWrapper);
        if (null==userSelect){
            throw new UsernameNotFoundException("用户名不对");
        }
        roleAndPermHandler(userSelect, securityUser, type);
        return securityUser;
    }

    /**
     * 角色和权限的处理
     * @param userSelect
     * @param securityUser
     */
    private void roleAndPermHandler(User userSelect, SecurityUser securityUser, Integer type) {
        //执行到此处，说明用户名正确
        //通过用户id查询权限和角色
        List<Role> roleList = userRoleMapper.findRoleByUserId(userSelect.getId());
        List<Menu> menuList = userRoleMapper.findPermByUserId(userSelect.getId());
        //这里就需要转换为集合
        List<String> roleAndPermList = convertListString(roleList,menuList);
        //封装返回对象
        Account account = new Account();
        account.setId(userSelect.getId());
        account.setUsername(userSelect.getUsername());
        account.setPassword(userSelect.getPassword());
        account.setType(type);
        //设置权限和角色
        securityUser.setAccount(account);
        securityUser.setRoleAndPerms(roleAndPermList);
    }

    /**
     * 将查询出来的角色和权限转换成List<String>类型的数组
     * @param roleList
     * @param menuList
     * @return
     */
    private List<String> convertListString(List<Role> roleList, List<Menu> menuList) {
        ArrayList<String> lists = new ArrayList<>();
        //将角色转换成集合
        for (int i = 0; i < roleList.size(); i++) {
            lists.add("ROLE_"+roleList.get(i).getName());
        }
        //将权限转换为集合
        for (int i = 0; i < menuList.size(); i++) {
            lists.add(menuList.get(i).getPermVal());
        }
        //最后将集合返回去
        return lists;
    }
}
